<template>
  <ContentWrap>
    <div class="customer-type-filter mb-10px flex flex-wrap items-center gap-3">
      <el-button @click="handleQuery" style="margin-left: auto"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
      <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      <el-button
        type="primary"
        plain
        @click="openForm('create')"
        v-hasPermi="['system:customer:create']"
      >
        <Icon icon="ep:plus" class="mr-5px" /> 新增
      </el-button>
      <el-button
        type="success"
        plain
        @click="handleExport"
        :loading="exportLoading"
        v-hasPermi="['system:customer:export']"
      >
        <Icon icon="ep:download" class="mr-5px" /> 导出
      </el-button>
      <el-button
        type="warning"
        plain
        @click="handleImport"
        v-hasPermi="['system:customer:import']"
      >
        <Icon icon="ep:upload" /> 导入
      </el-button>
      <el-button
        type="danger"
        plain
        :disabled="isEmpty(checkedIds)"
        @click="handleDeleteBatch"
        v-hasPermi="['system:customer:delete']"
      >
        <Icon icon="ep:delete" class="mr-5px" /> 批量删除
      </el-button>
    </div>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px query-form"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
    >
      <el-form-item label="客户姓名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder=""
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        />
      </el-form-item>
      <el-form-item label="跟进状态" prop="followUpStatus">
        <el-select
          v-model="queryParams.followUpStatus"
          placeholder=""
          clearable
          style="width: 90px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.FOLLOWUPSTATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>      
      <el-form-item label="客户星级" prop="starRating">
        <el-select
          v-model="queryParams.starRating"
          placeholder=""
          clearable
          style="width: 50px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.CUSTOMERSTARRATING)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="房产" prop="realestate">
        <el-select
          v-model="queryParams.realestate"
          placeholder=""
          clearable
          style="width: 70px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.REALESTATE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="公积金" prop="housingProvidentFund">
        <el-select
          v-model="queryParams.housingProvidentFund"
          placeholder=""
          clearable
          style="width: 80px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.HOUSINGPROVIDENTFUND)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="社保" prop="socialinsurance">
        <el-select
          v-model="queryParams.socialinsurance"
          placeholder=""
          clearable
          style="width: 70px;"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.SOCIALINSURANCE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="跟进时间" prop="followTime">
        <el-date-picker
          v-model="queryParams.followTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          clear-icon=""
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          style="width: 140px;"
        />
      </el-form-item>
      <el-form-item label="标记时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          clear-icon=""
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          style="width: 140px;"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder=""
          type="tel"
          clearable
          @keyup.enter="handleQuery"
          style="width: 100px;"
        />
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      border
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      :select-on-indeterminate="false"
      :height="540"
      :row-style="({ row }) => (0 === row.status ? { color: 'red' } : {})"
      @row-click="handleRowClick"
      @selection-change="handleRowCheckboxChange"
      @sort-change="handleSortChange"
    >
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
      <el-table-column :resizable="false" type="selection" align="center" width="40px" fixed="left" />
      <el-table-column :resizable="false" label="姓名" align="center" prop="username"  />
      <el-table-column :resizable="false" label="年龄" align="center" prop="age"  />
      <el-table-column :resizable="false" label="性别" align="center" prop="sex" >
        <template #default="scope">
          {{ getDictLabel(DICT_TYPE.SYSTEM_USER_SEX, scope.row.sex) }}
        </template>
      </el-table-column>
      <el-table-column :resizable="false" label="额度" align="center" prop="quota" />
      <!-- <el-table-column :resizable="false" label="跟进人" align="center" prop="followUpName"  /> -->
      <el-table-column :resizable="false" label="跟进状态" align="center" prop="followUpStatus" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.FOLLOWUPSTATUS" :value="scope.row.followUpStatus" />
        </template>
      </el-table-column>
      <el-table-column :resizable="false" label="客户星级" align="center" prop="starRating" >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CUSTOMERSTARRATING" :value="scope.row.starRating" />
        </template>
      </el-table-column>
      <el-table-column :resizable="false" label="客户属性" align="center" >
        <template #default="{ row }">
          <template v-if="!CustomerProps(row).length">无</template>
          {{ CustomerProps(row) }}
          <!-- <div class="tag-group">
          </div> -->
        </template>
      </el-table-column>
      <el-table-column :resizable="false" label="客户条件备注" align="center" prop="remark" width="145px" />
      <el-table-column :resizable="false" label="跟进情况备注" align="center" prop="followRemark" width="145px" />
      <el-table-column :resizable="false" label="跟进次数" align="center" prop="followUpFrequency" />
      <el-table-column
        :resizable="false"
        label="最后跟进时间"
        align="center"
        prop="followTime"
        :formatter="dateFormatter"
        sortable
        width="145px"
      >
        <template #header>
          最后跟进时间
          <span class="caret-wrapper custom">
            <i :style="{ 'border-bottom-color': 1 === queryParams.sortFollowOrder ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret ascending"></i>
            <i :style="{ 'border-top-color': 0 === queryParams.sortFollowOrder ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret descending"></i>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        :resizable="false"
        label="标记时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        sortable
        width="145px"
      >
        <template #header>
          标记时间
          <span class="caret-wrapper custom">
            <i :style="{ 'border-bottom-color': 1 === queryParams.sortcreateTime ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret ascending"></i>
            <i :style="{ 'border-top-color': 0 === queryParams.sortcreateTime ? 'var(--el-color-primary)' : 'var(--el-text-color-placeholder)'  }" class="sort-caret descending"></i>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        :resizable="false"
        align="center"
        width="145px"
        fixed="right">
        <template #default="scope">
          <el-button
            link
            v-if="'公海客户' == getDictLabel(DICT_TYPE.CUSTOMER_TYPE, scope.row.customerType)"
            type="primary"
            @click.stop="() => handleTake([scope.row.id])"
          >
            领取
          </el-button>
          <!-- @click.stop="openForm('update', scope.row.id)" -->
          <el-button
            link
            type="primary"
            @click.stop="() => handleRowClick(scope.row)"
            v-hasPermi="['system:customer:update']"
          >
            详情
          </el-button>
          <el-button
            link
            type="danger"
            @click.stop="handleDelete(scope.row.id)"
            v-hasPermi="['system:customer:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      :page-sizes="[50, 100]"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <MyCustomerForm ref="formRef" @success="getList" />

  <!-- 表单弹窗：添加/修改 -->
  <!-- <customerForm
    ref="formRef"
    @success="getList"
  /> -->

  <!-- 客户分配 -->
  <AssignDialog ref="assignDialogRef" @submit="handleAssign" />

  <!-- 客户导入表单组件 -->
  <ImportForm
    ref="importFormRef"
    @success="getList"
  />

  <!-- 跟进表单 -->
  <FollowUpDialog
    ref="followUpDialogRef"
    :get-info-method="MyCustomerApi.getMyCustomer"
    :info-list="list"
    :get-info-list-method="getList"
    :save="handleFollowUpSave"
    :get-history-method="info => customerApi.getRemarkHistory({ myCustomerId: info.id })"
    :get-loan-page-method="info => loanApi.getloanPage({ pageNo: 1, pageSize: 30, myCustomerId: info.id})"
    :show-assign-dialog="showAssignDialog"
  />
</template>

<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE, getDictLabel } from '@/utils/dict'
import { isEmpty } from '@/utils/is'
import { dateFo1rmatter, dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { customerApi, customer } from '@/api/system/customer'
import customerForm from '../customer/customerForm.vue'
import AssignDialog from '../customer/AssignDialog.vue'
import ImportForm from '../customer/ImportForm.vue'
import FollowUpDialog from './FollowUpDialog.vue'
import dayjs from 'dayjs'
import { cloneDeep, omit } from 'lodash-es'
import { hasPermission } from '@/directives/permission/hasPermi'
import { MyCustomerApi, MyCustomer } from '@/api/system/mycustomer'
import MyCustomerForm from './MyCustomerForm.vue'
import { info } from 'console'
import { loanApi } from '@/api/system/loan'

/** 标记客户 列表 */
defineOptions({ name: 'MyCustomer' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<MyCustomer[]>([]) // 列表的数据
provide('infoList', list);
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  username: undefined,
  mobile: undefined,
  createTime: [],
  starRating: undefined,
  realestate: undefined,
  housingProvidentFund: undefined,
  socialinsurance: undefined,
  followTime: [],
  followUpStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await MyCustomerApi.getMyCustomerPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
provide('getList', getList);

function CustomerProps(row) {
  return [
    {
      type: DICT_TYPE.REALESTATE,
      prop: 'realestate',
      validator: x => [0,1].includes(x),
    },
    {
      type: DICT_TYPE.HOUSINGPROVIDENTFUND,
      prop: 'housingProvidentFund',
      validator: x => [0].includes(x),
    },
    {
      type: DICT_TYPE.SOCIALINSURANCE,
      prop: 'socialinsurance',
      validator: x => [0].includes(x),
    }
  ]
  .filter(item => item.validator(row[item.prop]))
  .map(item => getDictLabel(item.type, row[item.prop]))
  .join('/');
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

function handleSortChange({ column, prop, order }) {
  function Value() {
    // 下标为 -1 则值为 undefined，正好对应不传
    const i = ['descending', 'ascending'].indexOf(order);
    return [0, 1][i];
  }

  function Prop() {
    return {
      followTime: 'sortFollowOrder',
      createTime: 'sortcreateTime',
    }[prop];
  }

  queryParams[Prop()] = Value();
  getList();
}

function handleFollowUpSave(info, infoInitial) {
  // 若某些字段值没变，则不传那些字段值
  // 目前有跟进状态、跟进备注
  const needCheckProps = ['followUpStatus', 'followRemark'];
  const isNoModified = prop => info.value[prop] == infoInitial.value[prop];
  const omitProps = needCheckProps.filter(isNoModified);
  return MyCustomerApi.updateMyCustomer(omit(info.value, omitProps.concat(['customerId'])));
}

const followUpList = ref([]);
function getFollowUpList() {
  return customerApi.getFollowUpList()
  .then(data => {
    followUpList.value = data;
  });
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await MyCustomerApi.deleteMyCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除标记客户 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await MyCustomerApi.deleteMyCustomerList(checkedIds.value);
    checkedIds.value = [];
    message.success(t('common.delSuccess'))
    await getList();
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: MyCustomer[]) => {
  checkedIds.value = records.map((item) => item.id!);
}

const followUpDialogRef = ref();
function handleRowClick(row, column) {
  if (column && 'selection' == column.type) {
    return;
  }
  followUpDialogRef.value.open(list.value.indexOf(row));
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await MyCustomerApi.exportMyCustomer(queryParams)
    download.excel(data, '标记客户.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

const assignDialogRef = ref()
function showAssignDialog(formState) {
  assignDialogRef.value.open(formState)
}
provide('showAssignDialog', showAssignDialog);

function handleAssign(payload) {
  if (!Boolean(payload.followUp.id)) {
    message.warning('请先选择分配人员')
    return
  }

  loading.value = true
  // 分配可选多人
  return customerApi
    .assign({
      customerType: payload.customerType,
      ids: payload.ids,
      followUpId: payload.followUp.id,
      followUpName: payload.followUp.nickname
    })
    .then(() => {
      message.success('已分配')
      getList()
      assignDialogRef.value.close()
      return
    })
    .finally(() => {
      loading.value = false
    })
}
provide('handleAssign', handleAssign);

function addMyCustomer() {}

/** 初始化 **/
onMounted(() => {
  getList();
  getFollowUpList();
})
</script>

<style scoped>
.customer-type-filter {
  background-color: #f5f7fa;
  padding: 6px 10px;
  border-radius: 10px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.customer-type-filter .el-button {
  height: 30px;
  font-size: 12px;
}

.customer-type-filter .el-button + .el-button {
  margin-left: 0;
}

.customer-type-filter .el-button.is-round {
  height: 28px;
}

.query-form {
  display: flex;
  flex-wrap: wrap;
  gap: 4px 12px;
  padding-bottom: 18px;
}

.query-form .el-button {
  height: 24px;
  padding: 4px 10px;
  font-size: 12px;
}

.query-form .el-form-item {
  margin: 0;
}

.query-form :deep(.el-form-item__content) {
  font-size: 12px;
}

.query-form :deep(.el-form-item__label),
.query-form :deep(.el-form-item__content) :where(.el-input, .el-select__wrapper, .el-range-input) {
  font-size: 12px;
}

.query-form :deep(.el-input__inner) {
  --el-input-inner-height: 22px;
}

.query-form :deep(.el-input__wrapper) {
  padding-left: 0;
  padding-right: 4px;
}

.query-form :deep(.el-date-editor .el-range-input) {
  width: 44%;
}

.query-form :deep(.el-date-editor.el-input__wrapper) {
  padding-right: 0;
}

.query-form :deep(.el-select__wrapper) {
  padding-left: 4px;
  padding-right: 6px;
  min-height: 24px;
  height: 22px;
  line-height: 22px;
}

.query-form :where(.el-date-editor.el-input, .el-date-editor.el-input__wrapper) {
  justify-content: left;
  padding-right: 0;
  --el-component-size: 24px;
}

.query-form :deep(.el-date-editor .el-range-separator) {
  flex: 0;
  width: 2px;
  padding-left: 2px;
  padding-right: 2px;
}

.filter-label {
  font-weight: 500;
  font-size: 14px;
}

.filter-btn {
  min-width: 80px;
  font-weight: 500;
}

:deep(.el-table) th {
  color: #666;
}

:deep(.el-table--default) .cell {
  padding-left: 2px;
  padding-right: 2px;
}

.tag-group {
  display: flex;
  justify-content: center;
}

/* 这些说不定以后还用得上 */
.tag-group > .dict-tag { margin-right: -1px; }
.tag-group > .dict-tag:not(:first-child):not(:last-child) :deep(.el-tag) { border-radius: 0; }
.tag-group > .dict-tag:first-child:last-child:last-child :deep(.el-tag) { border-radius: 4px; }

.tag-group > .dict-tag:first-child :deep(.el-tag) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

.tag-group > .dict-tag:last-child :deep(.el-tag) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.count-info {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  line-height: 1.25;
  margin-left: 8px;
}

.count-info .value {
  color: red;
  cursor: pointer;
  text-decoration: underline;
}

:deep([class="caret-wrapper"]) {
  display: none;
}
</style>